package com.abgame.test.javase.delayed;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ChengJianSheng
 * @since 2021/3/19
 */
@Slf4j
@Component
public class DelayQueueManager implements CommandLineRunner {

    private DelayQueue<DelayTask> queue = new DelayQueue<>();

    @Autowired
    private ParkOrderQueryHandler handler;

    @Override
    public void run(String... strings) throws Exception {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        DelayTask task = queue.take();
                        handler.handle(task);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void put(DelayTask task) {
        queue.put(task);
    }
}